import React, {useCallback, useEffect, useMemo, useState} from 'react'

// antd about
import {
  Form,
  Input,
  InputNumber,
  Select,
  Button,
  Table,
  Space,
  Modal,
  message,
  Image,
} from 'antd';

// 库存，销售，记录 的 axios
import {
  getInventories,
  getStocks,
  updateStockOfCell,
  getStocksWithID,
} from '../../api/stock'

import { addRecordData } from '../../api/records'

import {
  getOnSalesLength,
  getOnSalesUltimate,
  updateOnSaleAmountOrPrice,
  updateOnSaleDiscount,
} from '../../api/onSales'

import { generateAddSaleNum, generateUpdateDiscount } from '../../utils/generateRecord';

// redux
import { useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';

export default function OnSales() {

  // 注册 form
  const [sellForm] = Form.useForm()

  // 获取跳转路由的 navigate
  const navigate = useNavigate()

  // 注册 补充数量 表单
  const [form] = Form.useForm()

  // 注册 修改折扣 表单
  const [discountForm] = Form.useForm()

  // 获取 redux 里的用户数据
  const username = useSelector((state) => state.user.info)

  // 页数
  const [pageOrder, setPageOrder] = useState(1)

  // 页数内容个数
  const [pageSize, setPageSize] = useState(3)

  // 商品数据 state
  const [goodsData, setGoodsData] = useState([])

  // 库存数据
  const [stockData, setStockData] = useState([])

  // 商品分类 state
  const [inventories, setInventories] = useState()

  // 商品总数
  const [total, setTotal] = useState(1)

  // 当前选择分类
  const [inventoryId, setInventoryId] = useState()

  // 当前查询内容
  const [name_like, setName_like] = useState()

  // 合并所有查询= 》
  const getGoodsList = useCallback(async({_page, _limit, inventoryId, name_like, operate}) => {
    // 包含了分页+类别+名字的查询
    const res = await getOnSalesUltimate({_page, _limit, inventoryId, name_like})
    // 设置商品数据
    setGoodsData(res)
    // 设置页码
    setPageOrder(_page)
    // 设置当前页个数
    setPageSize(_limit)
    // 设置查询id
    setInventoryId(inventoryId)
    // 设置查询字符串
    setName_like(name_like)
    // 如果 operate 为重置
    if (operate === 'reset') {
      // 查询所有商品内容
      const all = await getOnSalesLength()
      setTotal(all)
    } else {
      // 设置查询到的商品总数
      const Inquire = await getOnSalesLength({inventoryId, name_like})
      setTotal(Inquire)
    }
  }, [])

  // 缓存商品分类 useEffect
  useEffect(() => {
    // 获取商品分类
    const Inventory = async() => {
      try {
        // try 语句块中放置可能会出现异常的代码
        let res = await getInventories()
        // 设置数据
        setInventories(res)
      } catch (error) {
        // catch 语句块中是出现异常后，解决异常问题的代码
        console.log('异常：', error)
      } finally {
        // finally 语句块是无论是否出现异常，最终都会执行的代码
      }
    }
    Inventory()

    // 获取商品数据
    const Stock = async() => {
      // 获取商品总数
      const res2 = await getStocks()
      setTotal(res2)

      getGoodsList({_page: pageOrder, _limit: pageSize, inventoryId, name_like})
    }
    Stock()
  }, [])

  // 触发搜索
  const onFinish = useCallback((values) => {
    // 如果查询全部商品则不传递 inventoryId
    values.select === 7 ? values.select = undefined : values.select
    // 发送请求
    getGoodsList({_page: pageOrder, _limit: pageSize, inventoryId: values.select, name_like: values.goodsName})
  }, [])

  // 触发重置
  const onReset = useCallback(() => {
    // 重置form
    form.resetFields()
    // 重置分页和查询数据
    setInventoryId(undefined)
    setName_like(undefined)
    setPageOrder(1)
    setPageSize(3)
    // 重新发送请求
    getGoodsList({_page: pageOrder, _limit: pageSize, inventoryId: undefined, name_like: undefined, operate: 'reset'})
  }, [])

  // 触发分页
  const pageSelect = useCallback(async(page, _pageSize) => {
    getGoodsList({_page: page, _limit: _pageSize, inventoryId, name_like})
  }, [])

  // 保存当前点击的列表
  const [nowClickRowData, setNowClickRowData] = useState()

  // 修改折扣
  const editDiscount = useCallback((record) => {
    setNowClickRowData(record)
    // 打开模态框
    setIsModalVisible2(true)
    // 提取库存数据
    getStock(record.stockId)
    // 设置输入框默认值
    discountForm.setFieldsValue({
      discount: (record.discount * 10),
    })
  }, [])

  // 模态框显示依赖
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isModalVisible2, setIsModalVisible2] = useState(false);

  // 表单 填入完成
  const handleOk = useCallback(async(values) => {
    console.log(values)
    // 计算差值
    const gap = values.amount - nowClickRowData.amount
    // 分别发送数据修改
    updateStockOfCell(stockData.id, {
      amount: (stockData.amount - gap),
    })
    //
    updateOnSaleAmountOrPrice(nowClickRowData.id, {
      amount: values.amount,
      price: values.sellPrice,
    })
    // 关闭模态框
    setIsModalVisible(false)
    // 文字提示
    message.success('成功修改' + nowClickRowData.name + '的数量和售价')
    // 生成记录
    addRecordData(generateAddSaleNum({
      name: nowClickRowData.name,
      username,
      gap,
    }))
    // 重新获取数据
    getGoodsList({_page: pageOrder, _limit: pageSize, inventoryId, name_like})
  }, [nowClickRowData, stockData])

  // 点击确认修改折扣的按钮
  const handleUpdateDiscount = useCallback(async() => {
    // 获取输入框的值并除以10
    const newDiscount = discountForm.getFieldValue('discount') / 10
    // 解构赋值 取出数据
    const { id, discount, name } = nowClickRowData
    // 修改后台数据
    updateOnSaleDiscount(id, newDiscount)
      .then((data) => {
        message.success('成功修改' + name + '的折扣')
      })
    // 添加更改记录
    addRecordData(generateUpdateDiscount({name, username, discount, newDiscount}))
    // 重新获取当前页面
    getGoodsList({_page: pageOrder, _limit: pageSize, inventoryId, name_like})
    // 关闭模态框
    setIsModalVisible2(false)
  }, [nowClickRowData])

  // 关闭模态框
  const handleCancel = useCallback(() => {
    setIsModalVisible(false);
  }, [isModalVisible])
  const handleCancel2 = useCallback(() => {
    setIsModalVisible2(false);
  }, [isModalVisible2])

  // 补充数量
  const supAmount = useCallback(async(record) => {
    // 保存点击
    setNowClickRowData(record)
    // 打开模态框1
    setIsModalVisible(true)
    // 提取库存数据
    getStock(record.stockId)
    // 设置初始值
    sellForm.setFieldsValue({
      amount: (record.amount),
      sellPrice: (record.price),
    })
  }, [])

  // 取消出售
  const delSale = useCallback((record) => {
    message.warn('本店微小，还未营业，善待库存！')
  }, [])

  // 获取对应商品的信息
  const getStock = useCallback(async(id) => {
    // 提取库存数据
    const stock = await getStocksWithID(id)
    // 保存对应商品的库存数据
    setStockData(stock)
  }, [])

  // 表格自定义渲染
  const columns = [
    {
      title: '预览图',
      dataIndex: 'imageUrl',
      key: 'imageUrl',
      render: (text) => <Image
        width={50}
        src={text}
      />,
    },
    {
      title: '商品名',
      dataIndex: 'name',
      key: 'name',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '折扣',
      dataIndex: 'discount',
      key: 'discount',
      render: (text) => (
        <span>{text === 1 ? '原价' : text * 10 + '折'}</span>
      ),
    },
    {
      title: '零售价(￥)',
      dataIndex: 'price',
      key: 'price',
      render: (text) => (
        <span>{(text).toFixed(2)}</span>
      ),
    },
    {
      title: '折后价(￥)',
      dataIndex: 'price',
      key: 'price',
      render: (text, record) => (
        <span>{(text * record.discount).toFixed(2)}</span>
      ),
    },
    {
      title: '出售数量',
      dataIndex: 'amount',
      key: 'amount',
    },
    {
      title: '操作',
      key: 'action',
      dataIndex: 'sellState',
      render: (text, record) => (
        <Space size="middle">
          <Button type='primary' onClick={editDiscount.bind(null, record)}>修改折扣</Button>
          <Button onClick={supAmount.bind(null, record)}>补充数量</Button>
          <Button danger onClick={delSale.bind(null, record)}>取消销售</Button>
        </Space>
      ),
    },
  ];

  const data = [
    {
      key: '1',
      name: 'John',
      lastName: 'Brown',
      age: 32,
      address: 'New York No. 1 Lake Park',
      tags: ['nice', 'developer'],
    },
  ];

  return (
    <>
      {/* 搜索 */}
      <Form
        form={form}
        name="horizontal_login"
        layout="inline"
        onFinish={onFinish}
      >
        <Form.Item
          name="select"
        >
          <Select
            style={{ width: 120 }}
            placeholder="请选择商品分类"
            options={inventories}
            fieldNames={{
              label: 'title',
              value: 'id',
            }}
          />
        </Form.Item>
        <Form.Item
          name="goodsName"
        >
          <Input
            placeholder="请输入查询商品名字"
          />
        </Form.Item>
        <Form.Item shouldUpdate>
          {() => (
            <Space size="middle">
              <Button
                type="primary"
                htmlType="submit"
              >
                查询
              </Button>
              <Button
                type="primary"
                onClick={onReset}
              >
              重置
              </Button>
            </Space>
          )}
        </Form.Item>
      </Form>

      {/* 表格 */}
      <Table
        dataSource={goodsData}
        columns={columns}
        rowKey='id'
        // rowSelection={{
        //   type: 'checkbox',
        // }}
        pagination={{
          position: ['topLeft'],
          pageSizeOptions: [1, 3, 5, 10],
          showSizeChanger: true,
          showQuickJumper: true,
          current: pageOrder,
          pageSize: pageSize,
          total,
          onChange: pageSelect,
        }}
      >
      </Table>

      {/* 添加数量 模态框 */}
      <Modal
        title="增加或减少销售数量"
        visible={isModalVisible}
        onCancel={handleCancel}
        keyboard
        footer={null}
      >
        <p>
          商品名称： {nowClickRowData ? nowClickRowData.name : ''}
        </p>
        <Form
          name="sellForm"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          // initialValues={}
          onFinish={handleOk}
          autoComplete="off"
          form={sellForm}
        >
          <p>
            库存数量：{isModalVisible ? (stockData.amount ? stockData.amount : '库存已无该商品，请及时补充货物') : '禁止通过其他手段查看'}
          </p>
          <br />
          <Form.Item
            name="amount"
            label="当前数量："
            rules={[{ required: true, message: '' }]}
          >
            <InputNumber
              min={1}
              max={(nowClickRowData && stockData ? nowClickRowData.amount + stockData.amount : 0)}
            />
          </Form.Item>
          <br />
          <Form.Item
            name="sellPrice"
            label="出售价格："
            rules={[{ required: true, message: '' }]}
          >
            <InputNumber
              min={stockData ? stockData.buyPrice : 0}
              step={0.01}
              addonAfter="￥"
            />
          </Form.Item>
          <Form.Item
            label=" "
            colon={false}
          >
            <Button type="primary" htmlType="submit">
              确认
            </Button>
          </Form.Item>
        </Form>
      </Modal>
      {/* 修改折扣 模态框 */}
      <Modal
        title="确认提示"
        visible={isModalVisible2}
        onOk={handleUpdateDiscount}
        onCancel={handleCancel2}
      >
        <Form
          form={discountForm}
          // initialValues={}
        >
          <Form.Item
            label="修改出售折扣"
            name="discount"
          >
            <InputNumber
              max={10}
              min={(stockData && nowClickRowData ? (stockData.buyPrice / nowClickRowData.price) * 10 : 0.1)}
              step={0.1}
              addonAfter="折"
            />
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}
